﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RN.ERP.Web.KaoHeService1;
using RN.ERP.Web.BzkModelService;
using Newtonsoft.Json;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.BzkModelServiceNew;
using RN.ERP.Web.Utilities;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// KaoHe 的摘要说明
    /// </summary>
    public class KaoHeHandler : BaseHandler
    {
        BasicService.BasicServiceClient basicService = new BasicService.BasicServiceClient();
        KaoHeService1.KaoHeServiceClient kaoheServiceClient = new KaoHeService1.KaoHeServiceClient();
        ProjectService.ProjectServiceClient projectService = new ProjectService.ProjectServiceClient();
        PersonService.PersonServiceClient personService = new PersonService.PersonServiceClient();

        public override void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            string scoretype = context.Request["scoretype"];
            string scoreitem = context.Request["scoreitem"];
            string corpID = context.Request["corpID"];
            string treeeID = context.Request["treeID"];
            string itemID = context.Request["itemID"];
            var deduckId = context.Request["deduckId"];
            var prizeId = context.Request["prizeId"];
            var type = context.Request["type"];
            var flowCode = context.Request["flowCode"];
            var advice = context.Request["advice"];
            string userguid = context.Request["userguid"];
            string gradeName = context.Request["gradeName"];

            string result = string.Empty;
            switch (action)
            {
                case "EvaluationItem":
                    result = GetCorpEvaluationItems(context);
                    break;
                case "SaveEvaluation":
                    result = SaveEvaluation(context);
                    break;
                case "GetEvaluationScoreList":
                    result = GetEvaluationScoreList(context);
                    break;
                case "GetEScore":
                    result = GetEScore(scoretype, scoreitem);
                    break;
                case "GetCorpQuality":
                    result = GetCorpQuality(corpID);
                    break;
                case "EvaluationState":
                    result = GetCorpEvaluationState(context);
                    break;
                case "GetScoreItems":
                    result = GetScoreItems(treeeID, itemID);
                    break;
                case "AuditDeduck":
                    result = AuditDeduck(deduckId, flowCode, advice, userguid);
                    break;
                case "AuditKaohe":
                    result = AuditKaohe(prizeId, flowCode, advice, type);
                    break;
                case "DeleteDeduck":
                    result = DeleteDeduck(deduckId);
                    break;
                case "CorpEvaluationSub":
                    result = AddCorpEvaluationSub(context);
                    break;
                case "BankEdit":
                    result = CompanyBankEdit(context);
                    break;
                case "CanshuZhiBiao":
                    result = CorpEvaluationParamsEdit(context);
                    break;
                case "CorpAttachInfo":
                    result = GetCorpAttachInfo(context);
                    break;
                case "GetCorpEvaluteScore":
                    result = GetCorpEvaluteScore(userguid, gradeName);
                    break;
                case "ProjectAchieveMentKH":
                    result = ProjectAchieveMentKH(userguid);
                    break;
                default:
                    break;
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(result);
        }

        /// <summary>
        /// 获取近一年内的招标代理业绩
        /// </summary>
        private string ProjectAchieveMentKH(string userguid)
        {
            ProjectServiceNew.ProjectServiceClient client = new ProjectServiceNew.ProjectServiceClient();

            BzkModelServiceNew.ProjectRecord conditon = new BzkModelServiceNew.ProjectRecord();
            Guid corpUserGuid;
            Guid.TryParse(userguid, out corpUserGuid);
            conditon.CorpGuid = corpUserGuid;
            int count = 0;
            double? totalZBMoney = 0;
            string resultStr = client.GetyjRecordList(out count, out totalZBMoney, "DL", 0, 0, JsonConvert.SerializeObject(conditon), "");
            var countNum = new { ProjectCount = count.ToString(), ProjectSumZj = (totalZBMoney != null ? Math.Round(Convert.ToDouble(totalZBMoney), 2).ToString() : "0") };
            return JsonConvert.SerializeObject(countNum);
        }

        private string DeleteDeduck(string deduckIDList)
        {
            string[] deduckIDstr = deduckIDList.TrimEnd(',').Split(',');
            BzkModelService.OperationResult result = new BzkModelService.OperationResult();
            result = JsonConvert.DeserializeObject<BzkModelService.OperationResult>(projectService.DeleteDeduck(deduckIDstr));
            return result.Message;
        }

        private string AuditDeduck(string deduckID, string flowCode, string advice, string userGuid)
        {
            try
            {
                string[] deduckIDstr = deduckID.TrimEnd(',').Split(',');
                BzkModelService.OperationResult result = new BzkModelService.OperationResult();
                string userInfo = projectService.GetUserInfo(userGuid, "");
                result = JsonConvert.DeserializeObject<BzkModelService.OperationResult>(projectService.AuditDeduckList(deduckIDstr, flowCode, advice, userInfo));
                if (result.Result)
                {
                    return "审核成功";
                }
                else
                {
                    return "审核失败";
                }
            }
            catch (Exception ex)
            {
                return "审核扣分失败" + ex.InnerException.Message;
            }
        }

        private string AuditKaohe(string prizeID, string flowCode, string advice, string type)
        {
            BzkModelService.OperationResult result = new BzkModelService.OperationResult();
            string[] idarray = { prizeID };
            if (type == "1")
            {
                result = JsonConvert.DeserializeObject<BzkModelService.OperationResult>(projectService.ModifyProjectPrizePunish(idarray, "audit", flowCode, advice));
            }
            else if (type == "2")
            {
                result = JsonConvert.DeserializeObject<BzkModelService.OperationResult>(projectService.ModifyPrizePunish(idarray, "audit", flowCode, advice));
            }
            else
            {
                result = JsonConvert.DeserializeObject<BzkModelService.OperationResult>(projectService.ModifyDeduck(idarray, "audit", flowCode, advice));
            }
            if (result.Result)
            {
                return "审核成功";
            }
            else
            {
                return "审核失败";
            }
        }

        /// <summary>
        /// 返回评分项及分值列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCorpEvaluationItems(HttpContext context)
        {
            string areaCode = string.Empty;
            string appId = string.Empty;
            int evaluationId = 0;
            int classId = 0;
            if (context.Request.Params["appId"] != null)
            {
                appId = context.Request.Params["appId"];
            }
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (context.Request.Params["evaluationId"] != null)
            {
                int.TryParse(context.Request.Params["evaluationId"].Trim(), out evaluationId);
            }
            if (context.Request.Params["classId"] != null)
            {
                int.TryParse(context.Request.Params["classId"].Trim(), out classId);
            }
            if (string.IsNullOrEmpty(areaCode) || string.IsNullOrEmpty(appId))
            {
                return "{\"Result\":false,\"Message\":\"数据错误！\"}";
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {
                string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
                //执行添加或修改操作
                try
                {
                    result = client.GetCorpEvaluationItems(evaluationId, appId, classId, areaCode);

                }
                catch { }
                return result;
            }
        }

        /// <summary>
        /// 返回评价上报状态
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCorpEvaluationState(HttpContext context)
        {
            string areaCode = string.Empty;
            int corpEvalId = 0;
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (context.Request.Params["corpEvalId"] != null)
            {
                int.TryParse(context.Request.Params["corpEvalId"].Trim(), out corpEvalId);
            }
            string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
            if (string.IsNullOrEmpty(areaCode) || corpEvalId == 0)
            {
                return result;
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {
                //执行添加或修改操作
                try
                {
                    result = client.GetCorpEvaluationState(corpEvalId, areaCode);

                }
                catch { }
                return result;
            }
        }

        /// <summary>
        /// 添加修改评分参数指标数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string CorpEvaluationParamsEdit(HttpContext context)
        {
            string areaCode = string.Empty;
            string corpUserGuid = string.Empty;
            string evaluationParams = string.Empty;
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (context.Request.Params["corpUserGuid"] != null)
            {
                corpUserGuid = context.Request.Params["corpUserGuid"];
            }
            if (context.Request.Params["data"] != null)
            {
                evaluationParams = context.Request.Params["data"];
            }
            string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
            if (string.IsNullOrEmpty(evaluationParams) || string.IsNullOrEmpty(corpUserGuid))
            {
                return result;
            }
            //转化数据对象
            var pams = JsonConvert.DeserializeObject<List<JsonEntity>>(evaluationParams);
            string valStr = "";
            foreach (var pam in pams)
            {
                valStr = pam.value.Trim('\"');//对象值为json格式的tb_WorkExperience对象
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {

                //执行添加或修改操作
                try
                {
                    result = client.CorpEvaluationParamsEdit(corpUserGuid, valStr, areaCode);
                }
                catch { }
                return result;
            }
        }

        /// <summary>
        /// 返回评分参数指标
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCorpAttachInfo(HttpContext context)
        {
            string areaCode = string.Empty;
            string corpUserGuid = string.Empty;
            string content = string.Empty;
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (context.Request.Params["corpUserGuid"] != null)
            {
                corpUserGuid = context.Request.Params["corpUserGuid"];
            }
            if (context.Request.Params["content"] != null)
            {
                content = context.Request.Params["content"];
            }
            string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
            if (string.IsNullOrEmpty(corpUserGuid) || string.IsNullOrEmpty(content))
            {
                return result;
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {
                try
                {
                    result = client.GetCorpAttachInfo(corpUserGuid, content, areaCode);

                }
                catch { }
                return result;
            }
        }

        /// <summary>
        /// 评分汇总
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string SaveEvaluation(HttpContext context)
        {
            string corpUserGuid = context.Request["corpUserGuid"];
            string snapGuid = context.Request["snapGuid"];
            string isrtUserGuid = context.Request["isrtUserGuid"];
            int classId = 0;
            if (!string.IsNullOrEmpty(context.Request["classId"]))
            {
                int.TryParse(context.Request["classId"], out classId);
            }
            string appId = context.Request["appId"];
            if (string.IsNullOrEmpty(isrtUserGuid) && UserInfo != null)
            {
                isrtUserGuid = UserInfo.CorpUserGuid;
            }
            var result = kaoheServiceClient.SaveCorpEvaluation(snapGuid, corpUserGuid, isrtUserGuid, appId, classId, UserInfo == null ? string.Empty : UserInfo.CurrentArea);
            return result;
        }

        public string GetEScore(string scoretype, string scoreitem)
        {
            ScoreItem conditon = new ScoreItem();
            int ScoreID = 0;
            Int32.TryParse(scoreitem, out ScoreID);
            conditon.ScoreID = ScoreID;

            var score = JsonConvert.DeserializeObject<List<eScore>>(basicService.GetEScore(int.Parse(scoretype), JsonConvert.SerializeObject(conditon))).FirstOrDefault();

            if (score != null)
            {
                return score.Score.ToString();
            }
            return string.Empty;
        }

        public string GetCorpQuality(string corpID)
        {
            List<QueryCorpQualityInfoCondition> list = new List<QueryCorpQualityInfoCondition>();
            QueryCorpQualityInfoCondition condition = new QueryCorpQualityInfoCondition();
            list.Add(condition);
            EnterpriseServiceClient entService = new EnterpriseServiceClient();
            IList<tb_Corp_Quality> qualityList = JsonConvert.DeserializeObject<IList<tb_Corp_Quality>>(entService.GetCompanyQualities(corpID
                , JsonConvert.SerializeObject(list), ""));
            var query = qualityList.Where(q => q.IsMain == true).FirstOrDefault();
            return JsonConvert.SerializeObject(query);
        }

        private string GetEvaluationScoreList(HttpContext context)
        {
            string corpUserGuid = context.Request["corpUserGuid"];
            string snapGuid = context.Request["snapGuid"];
            //string isrtUserGuid = context.Request["isrtUserGuid"];
            //if (string.IsNullOrEmpty(isrtUserGuid) && UserInfo != null)
            //{
            //    isrtUserGuid = UserInfo.CorpUserGuid;
            //}
            string roleIds = RN.ERP.Web.Utilities.KaoheRoleIDHelp.GetRoleIds(UserInfo.RoleId);
            var result = kaoheServiceClient.GetCorpEvaluationScoreList(snapGuid, corpUserGuid, roleIds, UserInfo == null ? string.Empty : UserInfo.CurrentArea);
            return result;
        }

        public string GetScoreItems(string treeID, string itemID)
        {
            int ItemID;
            Int32.TryParse(itemID, out ItemID);
            int TreeID;
            Int32.TryParse(treeID, out TreeID);
            string corpEvaluationSub = kaoheServiceClient.GetCorp_EvaluationSub(ItemID, TreeID);
            var query = JsonConvert.DeserializeObject<CorpEvaluationSub>(corpEvaluationSub);
            if (query != null)
            {
                return query.TermsIds;
            }
            return string.Empty;
        }

        /// <summary>
        /// 添加单项评分记录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string AddCorpEvaluationSub(HttpContext context)
        {
            int treeId = 0;
            int itemId = 0;
            Decimal score = 0;
            if (context.Request.Params["treeId"] != null)
            {
                int.TryParse(context.Request.Params["treeId"].Trim(), out treeId);
            }
            if (context.Request.Params["itemId"] != null)
            {
                int.TryParse(context.Request.Params["itemId"].Trim(), out itemId);
            }
            if (context.Request.Params["score"] != null)
            {
                Decimal.TryParse(context.Request.Params["score"].Trim(), out score);
            }

            string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
            if (treeId == 0 || itemId == 0)
            {
                return result;
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {

                try
                {
                    ModelService.CorpEvaluationSub subInfo = new ModelService.CorpEvaluationSub();
                    subInfo.TreeId = treeId;
                    subInfo.ItemId = itemId;
                    subInfo.IsDel = false;
                    subInfo.TermsIds = "";
                    subInfo.Score = score;
                    subInfo.Remark = context.Request.Params["remark"];
                    result = client.AddCorpEvaluationSub(JsonConvert.SerializeObject(subInfo));
                }
                catch { }
                return result;
            }
        }

        /// <summary>
        /// 修改企业开户行
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string CompanyBankEdit(HttpContext context)
        {
            string corpGuid = string.Empty;
            string areaCode = string.Empty;
            string bankName = string.Empty;
            string bankAccNo = string.Empty;
            if (context.Request.Params["areaCode"] != null)
            {
                areaCode = context.Request.Params["areaCode"];
            }
            if (context.Request.Params["bankName"] != null)
            {
                bankName = context.Request.Params["bankName"].Trim();
            }
            if (context.Request.Params["bankAccNo"] != null)
            {
                bankAccNo = context.Request.Params["bankAccNo"].Trim();
            }
            if (context.Request.Params["corpGuid"] != null)
            {
                corpGuid = context.Request.Params["corpGuid"].Trim();
            }
            string result = "{\"Result\":false,\"Message\":\"数据错误！\"}";
            if (string.IsNullOrEmpty(corpGuid) || string.IsNullOrEmpty(bankName) || string.IsNullOrEmpty(bankAccNo))
            {
                return result;
            }
            using (KaoHeService1.KaoHeServiceClient client = new KaoHeService1.KaoHeServiceClient())
            {
                try
                {
                    result = client.CompanyBankEdit(corpGuid, bankName, bankAccNo, areaCode);
                }
                catch { }
                return result;
            }
        }

        private string GetCorpEvaluteScore(string corpUserGuid, string gradeName)
        {
            double score = 0;
            int empCount = personService.GetManagerZbRegisterByZBDL(corpUserGuid);
            switch (gradeName)
            {
                case "甲级":
                    if (empCount > 20)
                    {
                        score += (empCount - 20) * 0.1;
                    }
                    break;
                case "乙级":
                case "暂定级":
                    if (empCount > 12)
                    {
                        score += (empCount - 12) * 0.1;
                    }
                    break;

                default:
                    break;
            }
            return score.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
